<?php


namespace App\Http\Controllers;

use App\Internals\CourseInternal;
use App\Models\UserCourse;
use App\Models\UserStatus;

class StatusController extends Controller
{
    /*
     * @api get /study-api/status 用户学习状态
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *      "currentLevel[当前等级]":1,
     *      "wordCount[词汇量]":100
     *  }
     * }
     */
    public function index()
    {
        /** @var UserStatus $statusObj */
        $statusObj = UserStatus::where('user_id', $this->userId)->first();
        if ($statusObj) {
            if (!$statusObj->getCurrentLevel()) {
                // 根据购买的课程自动选择level
                /** @var UserCourse $currentCourse */
                $currentCourse = UserCourse::getCurrent($this->userId);
                if ($currentCourse) {
                    $currentLevel = $currentCourse->getLevel();
                    $statusObj->setCurrentLevel($currentLevel);
                    $statusObj->save();
                }
            }
            $status = [
                'currentLevel' => $statusObj->getCurrentLevel(),
                'testLevel' => $statusObj->getTestLevel(),
                'wordCount' => $statusObj->getWordCount(),
                'dubCount' => $statusObj->getDubCount()
            ];
        } else {
            // 初始化
            $statusObj = new UserStatus();
            $statusObj->setUserId($this->userId);
            $statusObj->save();
            $status = [
                'currentLevel' => 0,
                'testLevel' => 0,
                'wordCount' => 0,
                'dubCount' => 0
            ];
        }
        return $this->sendSuccessJson($status);
    }

    /*
     * @api get /study-api/recommend 推荐学习
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *      "currentLevel[当前等级]":1,
     *      "wordCount[词汇量]":100
     *  }
     * }
     */
    public function getRecommend()
    {
        // 用户未评测未学习，则默认读取Level 1 第一本绘本的封面。点击“开始学习”则进入评测环节
        // 用户已评测未学习，则默认读取该评测结果等级的第一本绘本封面，点击“开始学习”则进入到对应的绘本学习页面
        $isTest = 1;
        /** @var UserCourse $currentCourse */
        $currentCourse = UserCourse::getCurrent($this->userId);
        if ($currentCourse) {
            $level = $currentCourse->getLevel();
        } else {
            $level = UserStatus::where('user_id', $this->userId)->value('test_level');
            if (!$level) {
                $isTest = 0;
            } else {
                $level = 1;
            }
        }
        $course = CourseInternal::getLevelFirstLesson($level);

        $result = [
            'isTest' => $isTest,
            'cover' => $course['cover'],
            'lessonId' => $course['firstLessonId']
        ];
        return $this->sendSuccessJson($result);
    }
}
